package com.shujia.day18;

/*
    同步方法的锁对象
 */
class Window3 implements Runnable {
    static int tickets = 200;
    int i = 0;

    @Override
    public void run() {
        while (true) {
            if (i % 2 == 0) {
                synchronized (Window3.class) {
                    if (tickets > 0) { // 1
                        try {
                            // t1
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        System.out.println("当前 " + Thread.currentThread().getName() + " 正在出售第 " + (tickets--) + " 张票");
                    }
                }
            } else {
                sell();
            }

            i++;
        }
    }

    public synchronized static void sell() {
        if (tickets > 0) { // 1
            try {
                // t1
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("当前 " + Thread.currentThread().getName() + " 正在出售第 " + (tickets--) + " 张票");
        }
    }


//    public synchronized void sell() {
//        if (tickets > 0) { // 1
//            try {
//                // t1
//                Thread.sleep(20);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//
//            System.out.println("当前 " + Thread.currentThread().getName() + " 正在出售第 " + (tickets--) + " 张票");
//        }
//    }
}


public class SellTicketsDemo3 {
    public static void main(String[] args) {
        Window3 window3 = new Window3();

        Thread t1 = new Thread(window3, "窗口1");
        Thread t2 = new Thread(window3, "窗口2");
        Thread t3 = new Thread(window3, "窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}